<?php
    include_once("../action/checkAuthenticationAction.php");
    include_once("../service/categoryService.php");
    
    include_once("../util/authUtil.php");
    $perm_array = $_SESSION["permissions"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<title>Dashboard</title>
	<?php include("import-css.php");?>	
    <style>
        #sortable1, #sortable2 { list-style-type: none; margin: 5px 0 0 0; padding: 0 0 2.5em; float: left; margin-right: 10px; border:1px solid black; min-height:20px; min-width:160px; border-radius:4px;}
        #sortable1 li, #sortable2 li {cursor:pointer; margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; min-width:140px;}
		
		#sortable3, #sortable4 { list-style-type: none; margin: 5px 0 0 0; padding: 0 0 2.5em; float: left; margin-right: 10px; border:1px solid black; min-height:20px; min-width:160px; border-radius:4px;}
        #sortable3 li, #sortable4 li {cursor:pointer; margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; min-width:140px;}
    </style>
</head>
<body>
	<?php include("header.php");?>
    
    <div class="container-fluid">
		<div class="row-fluid">
            <!--Menu-->
            <?php include("menu.php");?>
            <?php
                $action = isset($_GET["action"]) ? $_GET["action"] : 8;
                if($action == 9){
                    $cat_id = $_GET["id"];
                    $edit_category = getCategory($cat_id);
                }
            ?>
            <!--Content-->
            <div class="box span10 offset2">
                <div class="box-content">
                <?php
                    if(!authUtil(array("edit category","create category","view category"),$perm_array,false)){
                        echo "<script>window.location.href='../admin/index.php';</script>";
                    }
                    $require_perm = array("edit category","create category");
                ?>
                    <form class="form-horizontal" method="POST" action="<?php if(authUtil($require_perm,$perm_array,false)){ if ($action == 8 && authUtil(array("create category"),$perm_array,true)){echo "../action/newCategoryAction.php";} if($action == 9 && authUtil(array("create category","edit category"),$perm_array,false)){echo "../action/editCategoryAction.php";}}?>" id="new_category_form">
                        <div class="control-group">
                            <label for="categoryTitle" class="control-label">Nhóm sản phẩm</label>
                            <div class="controls">
                                <input required type="text" value="<?php echo ($action == 9 ?  $edit_category["CAT_NAME"] : ""); ?>" id="categoryTitle" name="categoryTitle" class="input-xlarge focused">
                            </div>
                        </div>
                                                
                        <div class="control-group">
                            <label class="control-label" for="selectError">Thuộc nhóm</label>
                            <div class="controls">
                                 <select id="parent_category" name="parent_category" onchange='removeUnavailableOpt($(this).val());removeUnavailableAttr($(this).val());' <?php if($action==9) {echo isAbleChangeParent($edit_category["CAT_ID"]) ? "" : "disabled";}?> >
                                    <option value=''>----------</option>
                                    <?php
                                    $categories = getAllCategory();
                                        while($category = mysql_fetch_array($categories)){
											if($category["CAT_ID"] != $edit_category["CAT_ID"]){
												echo "<option value='".$category["CAT_ID"]."' ";
												if(isset($edit_category["CAT_PARENT_ID"]))
													echo $edit_category["CAT_PARENT_ID"] == $category["CAT_ID"] ? "selected" : "";
												echo " >".$category["CAT_NAME"]."</option>";
											}
                                        }
                                    ?>
                                 </select>
                            </div>
                        </div>
                        
                        <div class="control-group">
                            <label for="categoryOrder" class="control-label">Độ ưu tiên</label>
                            <div class="controls">
                                <select id="categoryOrder" name="categoryOrder" novalidate="novalidate">
                                    <?php
                                        for($i=0;$i<=100;$i++){
                                    ?>
                                        <option <?php echo (($action == 9 && $i == $edit_category["CAT_ORDER"]) ? "selected" : "" ); ?> value="<?php echo $i; ?>"><?php echo $i; ?></option>
                                    <?php
                                        }
                                    ?>
                                </select>
                            </div>
                        </div>
						<!--ATTRIBUTES-->
                        <div class="control-group">
                            <label class="control-label">Thuộc tính</label>
                            <div class="controls" id="attrControlGroup">
                                <input type="text" value="" id="attributeTitle" class="input-xlarge focused">
                                <button type="button" class="btn btn-primary" onclick="addAttribute($('#attributeTitle').val(),$('#sortable2'));">Tạo mới</button>
                                <br/>
                                <ul id="sortable1" class="connectedSortable">
                                        <?php
                                            if($action == 8){
                                                $attributes = getAllAttribute();
                                            }else if($action == 9){
                                                //echo "here";
                                                //echo $edit_category["CAT_ID"] ."/". $edit_category["CAT_PARENT_ID"];
                                                $attributes = getAvailableAttributeOfCategory($edit_category["CAT_ID"],$edit_category["CAT_PARENT_ID"]);
                                            }
                                            while($attr = mysql_fetch_array($attributes)){
                                                echo "<li class='ui-state-default' value='".$attr["ATT_ID"]."'>".$attr["ATT_NAME"];
                                                if(isAttDeleteTable($attr["ATT_ID"]) == 1){
                                                    echo "<a style='float:right;' onclick='deleteAtt(".$attr["ATT_ID"].",$(this));'>X</a>";
                                                }
                                                echo "<input type='hidden' name='selectedAtts[]' value='".$attr["ATT_ID"]."'/>";
                                                echo "</li>";
                                            }
                                        ?>
                                </ul>
                                <div style="float:left;margin-right:5px;">===></div>
                                <ul id="sortable2" name="sortable2[]" class="connectedSortable">
                                    <?php
                                        if($action == 9){
                                            $attributes = getAttributesOfCategory($edit_category["CAT_ID"]);
                                        }
                                        while($attr = mysql_fetch_array($attributes)){
                                            echo "<li class='";
                                            if(isAttributeUnassignable($attr["ATT_ID"],$edit_category["CAT_ID"])){
                                                echo "ui-state-default"; 
                                            }else{
                                                echo "unsortable";                                                
                                            }
                                            echo "' value='".$attr["ATT_ID"]."'>".$attr["ATT_NAME"];
                                            if(isAttDeleteTable($attr["ATT_ID"]) == 1){
                                                echo "<a style='float:right;' onclick='deleteAtt(".$attr["ATT_ID"].",$(this));'>X</a>";
                                            }
                                            echo "<input type='hidden' name='selectedAtts[]' value='".$attr["ATT_ID"]."'/>";
                                            echo "</li>";
                                        }
                                    ?>                                    
                                </ul>
                            </div>
                        </div>
						<!--OPTIONS-->
						<div class="control-group">
                            <label class="control-label">Lựa chọn phụ</label>
                            <div class="controls" id="optControlGroup">
                                <input type="text" value="" id="optionTitle" class="input-xlarge focused">
                                <button type="button" class="btn btn-primary" onclick="addOption($('#optionTitle').val(),$('#sortable4'));">Tạo mới</button>
                                <br/>
                                <ul id="sortable3" class="connectedSortable1">
                                        <?php
                                            if($action == 8){
                                                $options = getAllOption();
                                            }else if($action == 9){
                                                //echo "here";
                                                //echo $edit_category["CAT_ID"] ."/". $edit_category["CAT_PARENT_ID"];
                                                $options = getAvailableOptionOfCategory($edit_category["CAT_ID"],$edit_category["CAT_PARENT_ID"]);
                                            }
                                            while($opt = mysql_fetch_array($options)){
                                                echo "<li class='";
                                                if(isOptionUnassignable($attr["ATT_ID"],$edit_category["CAT_ID"])){
                                                    echo "ui-state-default"; 
                                                }else{
                                                    echo "unsortable";                                                
                                                }
                                                echo "' value='".$opt["OPP_ID"]."'>".$opt["OPP_NAME"];
                                                if(isOptionDeleteTable($opt["OPP_ID"]) == 1){
                                                    echo "<a style='float:right;' onclick='deleteOpt(".$opt["OPP_ID"].",$(this));'>X</a>";
                                                }
                                                echo "<input type='hidden' name='selectedOpts[]' value='".$opt["OPP_ID"]."'/>";
                                                echo "</li>";
                                            }
                                        ?>
                                </ul>
                                <div style="float:left;margin-right:5px;">===></div>
                                <ul id="sortable4" name="sortable4[]" class="connectedSortable1">
                                    <?php
                                        if($action == 9){
                                            $options = getOptionsOfCategory($edit_category["CAT_ID"]);
                                        }
                                        while($attr = mysql_fetch_array($options)){
                                            echo "<li class='ui-state-default' value='".$attr["OPP_ID"]."'>".$attr["OPP_NAME"];
                                            if(isOptionDeleteTable($attr["OPP_ID"]) == 1){
                                                echo "<a style='float:right;' onclick='deleteOpt(".$attr["OPP_ID"].",$(this));'>X</a>";
                                            }
                                            echo "<input type='hidden' name='selectedOpts[]' value='".$attr["OPP_ID"]."'/>";
                                            echo "</li>";
                                        }
                                    ?>                                    
                                </ul>
                            </div>
                        </div>
                        <?php
                            $require_perm = array("edit category","create category");
                            if(authUtil($require_perm,$perm_array,false)){
						?>
                        <center>
                        <button type="submit" class="btn btn-primary"><?php echo (($action == 8) ? "Tạo mới" : "Cập nhật"); ?></button>
                        </center>
                        <input type="hidden" name="edit_cate_id" id="edit_cate_id" value="<?php echo isset($edit_category["CAT_ID"])?$edit_category["CAT_ID"]:""; ?>"/>
                        <?php
                            }
                        ?>
                    </form>
                </div>
                
            </div><!--/span-->
        </div>
    </div>

    <?php include("footer.php");?>
		
	</div><!--/.fluid-container-->

	<?php include("import-js.php");?>	

    <script>
    $(function() {
		$( "#sortable1, #sortable2" ).sortable({
            connectWith: ".connectedSortable",
            items: "li:not(.unsortable)"
        }).disableSelection();
		
		$( "#sortable3, #sortable4" ).sortable({
            connectWith: ".connectedSortable1",
            items: "li:not(.unsortable)"
		}).disableSelection();
				
        $("#new_category_form").validate({
            submitHandler: function(form) {
			//Do not submit attributes and options in left-side list
                options1 = $("#sortable1").find("input");
                options1.each(function(){
                    $(this).attr("name","");
                    console.log($(this).attr("name",""));
                });
				
				options2 = $("#sortable3").find("input");
                options2.each(function(){
                    $(this).attr("name","");
                    console.log($(this).attr("name",""));
                });
                $(form).submit();
            }
        });
    });
    function addAttribute(title,destination){
        $(destination).append("<li class='ui-state-default' value='0'>"+title+"*<a style='float:right;' onclick='deleteAtt(0,$(this));'>X</a><input type='hidden' name='selectedAtts[]' value='"+title+"'/></li>");
        $("#attributeTitle").val("");
        
    }
	function addOption(title,destination){
        $(destination).append("<li class='ui-state-default' value='0'>"+title+"*<a style='float:right;' onclick='deleteOpt(0,$(this));'>X</a><input type='hidden' name='selectedOpts[]' value='"+title+"'/></li>");
        $("#optionTitle").val("");}
	
    function deleteAtt(attId,option){
        if(attId == 0){
            $(option).parent().remove();
        }else{
                $.ajax({
                type: "GET",
                url: "../action/ajax/deleteAttributeAction.php",
                data: { id: attId }
            }).done(function( data ) {
			console.log(data);
                if(data == 1){
                    deletetedOpt = $(option).parent();
                    deletetedOpt.remove();
                }else{
                    alert("delete failed");
                }
            });
        }
    }
	function deleteOpt(optId,option){
        if(optId == 0){
            $(option).parent().remove();
        }else{
                $.ajax({
                type: "GET",
                url: "../action/ajax/deleteOptionAction.php",
                data: { id: optId }
            }).done(function( data ) {
			console.log(data);
                if(data == 1){
                    deletetedOpt = $(option).parent();
                    deletetedOpt.remove();
                }else{
                    alert("delete failed");
                }
            });
        }
    }
	
	function removeUnavailableAttr(parentCategoryId){
        $.ajax({
            type: "GET",
            url: "../action/ajax/getAvailableAttributeOfParentCategory.php",
            data: { cateId: parentCategoryId }
        }).done(function( data ) {
            options1 = $("#sortable1").find("li");
            options2 = $("#sortable2").find("li");
            $.each(options1, function(){
               if($(this).val() != 0){
                   $(this).remove();
               }                       
            });
            $.each(options2, function(){
               if($(this).val() != 0){
                   $(this).remove();
               }
            });                    
            
            avaiList = $("#sortable1");
			pairs = data.split("/\s*;\s*/");
            if (!(pairs[0] === "")){
                $.each(pairs, function(number){
                    pair = pairs[number];
                    id = pair.split("@")[0];
                    title = pair.split("@")[1];
                    deletetable = pair.split("@")[2];
					if(typeof title != 'undefined'){
						if(deletetable == "1"){
							avaiList.append("<li class='ui-state-default' value='"+id+"'>"+title+"<input type='hidden' name='selectedAtts[]' value='"+id+"'/><a style='float:right;' onclick='deleteAtt("+id+",$(this));'>X</a></li>");
						}else{
							avaiList.append("<li class='ui-state-default' value='"+id+"'>"+title+"<input type='hidden' name='selectedAtts[]' value='"+id+"'/></li>");
						}
					}
                });

            }
        });
        
    }
    
    function removeUnavailableOpt(parentCategoryId){
        $.ajax({
            type: "GET",
            url: "../action/ajax/getAvailableOptionOfParentCategory.php",
            data: { cateId: parentCategoryId }
        }).done(function( data ) {
            options1 = $("#sortable3").find("li");
            options2 = $("#sortable4").find("li");
            $.each(options1, function(){
               if($(this).val() != 0){
                   $(this).remove();
               }                       
            });
            $.each(options2, function(){
               if($(this).val() != 0){
                   $(this).remove();
               }
            });                    
            
            avaiList = $("#sortable3");
            pairs = data.split("/\s*;\s*/");
                $.each(pairs, function(number){
                    pair = pairs[number];
                    id = pair.split("@")[0];
                    title = pair.split("@")[1];
                    deletetable = pair.split("@")[2];
					if(typeof title != 'undefined'){
						if(deletetable == "1"){
							avaiList.append("<li class='ui-state-default' value='"+id+"'>"+title+"<input type='hidden' name='selectedOpts[]' value='"+id+"'/><a style='float:right;' onclick='deleteOpt("+id+",$(this));'>X</a></li>");
						}else{
							avaiList.append("<li class='ui-state-default' value='"+id+"'>"+title+"<input type='hidden' name='selectedOpts[]' value='"+id+"'/></li>");
						}
					}                    
                });
        });
        
    }
    </script> 
</body>
</html>

